<template>
  <div>
    <el-dialog
        :visible.sync="addDialog"
        center
        width="30%"
        :title="title"
        top="50px"
        :close-on-click-modal="false"
    >
      <div class="content">
        <p>
          <span>提成类型：</span>
          <el-select
              :disabled="disabledOp"
              @change="changeType"
              v-model="commissionTypeId"
              style="width: 300px"
              size="small"
              placeholder="请选择提成类型"
          >
            <el-option
                v-for="(item, index) in commissionList"
                :label="item.commissionType"
                :value="item.id"
                :key="index"
            ></el-option>
          </el-select>
        </p>
        <div v-if="commissionTypeId && commissionTypeId != 11">
          <p v-if="![2,3,6,7].includes(commissionTypeId)">
            <span>订单名称：</span>
            <el-select
                filterable
                remote
                :disabled="disabledOp"
                :remote-method="inputChange"
                @input="changeVal"
                value-key="orderId"
                clearable
                v-model="orderId"
                size="small"
                style="width: 300px"
                placeholder="请选择"
            >
              <el-option
                  v-for="item in saleNameList"
                  :key="item.orderId"
                  :label="item.storeName"
                  :value="item"
              >
              </el-option>
            </el-select>
          </p>
          <div>
            <p v-if="![6, 9].includes(commissionTypeId)">
              <span>相关人员：</span>
              <el-select
                  multiple
                  v-model="data.pickerList"
                  filterable
                  style="width: 300px"
                  size="small"
                  placeholder="请选择提成人员"
              >
                <el-option
                    v-for="(item, index) in userList"
                    :label="item.userName"
                    :value="item.id"
                    :key="index"
                ></el-option>
              </el-select>
            </p>
            <p v-if="commissionTypeId == 9">
              <span>老员工：</span>
              <el-select
                  multiple
                  v-model="oldPicker"
                  filterable
                  style="width: 300px"
                  size="small"
                  placeholder="请选择提成人员"
              >
                <el-option
                    v-for="(item, index) in oldList"
                    :label="item.userName"
                    :value="item.id"
                    :key="index"
                ></el-option>
              </el-select>
            </p>
            <p v-if="commissionTypeId == 9">
              <span>新员工：</span>
              <el-select
                  multiple
                  v-model="newPicker"
                  filterable
                  style="width: 300px"
                  size="small"
                  placeholder="请选择提成人员"
              >
                <el-option
                    v-for="(item, index) in newList"
                    :label="item.userName"
                    :value="item.id"
                    :key="index"
                ></el-option>
              </el-select>
            </p>
          </div>
          <p>
            <span>提成产生时间：</span>
            <el-date-picker
                v-model="data.commissionTime"
                type="date"
                style="width: 300px"
                size="small"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
            >
            </el-date-picker>
          </p>
        </div>

        <!--        所属仓库-->
        <div v-if="[1,4,8,13,7,9,6].includes(commissionTypeId)&&title=='分配人员'">
          <p>
            <span>所属仓库：</span>
            <el-select
                v-model="data.areaId"
                clearable
                placeholder="请按区域搜索"
                size="small"
                style="width: 300px"
            >
              <el-option
                  v-for="item in areaData"
                  :key="item.area"
                  :label="item.areaName"
                  :value="item.area"
              >
              </el-option>
            </el-select>
          </p>
        </div>
        <div v-if="[1,3,4,5,6,7,8,9,2,10,13].includes(commissionTypeId)&&title=='新增提成'">
          <p>
            <span>所属仓库：</span>
            <el-select
                v-model="data.areaId"
                clearable
                placeholder="请按区域搜索"
                size="small"
                style="width: 300px"
            >
              <el-option
                  v-for="item in areaData"
                  :key="item.area"
                  :label="item.areaName"
                  :value="item.area"
              >
              </el-option>
            </el-select>
          </p>
        </div>
        <!--   材料提成(1)/门店卸货提成(4)/上门售后提成(7)     -->
        <div v-if="[1, 4, 7].includes(commissionTypeId)">
          <p>
            <span>零时工数量：</span>
            <el-input-number
                size="small"
                style="width: 300px"
                v-model="data.tempWorkerNum"
            ></el-input-number>
          </p>
          <p>
            <span>提成总额：</span><span>{{ commissionCount }}</span>
          </p>
        </div>
        <!-- 新增单提成 -->
        <div v-if="[6,7].includes(commissionTypeId)">
          <p>
            <span>店铺名称：</span>
            <el-input
                v-model="data.storeName"
                clearable
                placeholder="请输入店铺名称"
                size="small"
                style="width: 300px"
            >
            </el-input>
          </p>
          <p>
            <span>所属品牌：</span>
            <el-select
                v-model="data.brandId"
                clearable
                placeholder="请选择品牌"
                size="small"
                style="width: 300px"
            >
              <el-option
                  v-for="item in systemList"
                  :key="item.id"
                  :label="item.systemName"
                  :value="item.id"
              >
              </el-option>
            </el-select>
          </p>
        </div>
        <!--   仓库装货提成(2)     -->
        <div v-if="commissionTypeId == 2">
          <p>
            <span>零时工数量：</span>
            <el-input-number
                size="small"
                style="width: 300px"
                v-model="data.tempWorkerNum"
            ></el-input-number>
          </p>
          <p>
            <span>车型配置：</span>
            <el-select
                @change="handleChange"
                v-model="data.vehicleModelId"
                style="width: 300px"
                size="small"
                placeholder="请选择车型配置"
            >
              <el-option
                  v-for="(item, index) in carData"
                  :label="item.vehicleModelName"
                  :value="item.id"
                  :key="index"
              ></el-option>
            </el-select>
          </p>
          <p>
            <span>提成总额：</span><span>{{ commissionCount }}</span>
          </p>
        </div>
        <!--   仓库装货提成(3)     -->
        <div v-if="commissionTypeId == 3">
          <p>
            <span>车型配置：</span>
            <el-select
                @change="handleChange"
                v-model="data.vehicleModelId"
                style="width: 300px"
                size="small"
                placeholder="请选择车型配置"
            >
              <el-option
                  v-for="(item, index) in carData"
                  :label="item.vehicleModelName"
                  :value="item.id"
                  :key="index"
              ></el-option>
            </el-select>
          </p>
          <p>
            <span>提成总额：</span><span>{{ commissionCount }}</span>
          </p>
          <p>
            <span>零时工数量：</span>
            <el-input-number
                size="small"
                style="width: 300px"
                v-model="data.tempWorkerNum"
            ></el-input-number>
          </p>
        </div>
        <!--  距离补贴提成(5)     -->
        <div v-if="commissionTypeId == 5">
          <p>
            <span>出发位置：</span>
            <el-input
                size="small"
                style="width: 300px"
                v-model="data.startLocation"
                placeholder="请输入出发位置"
            ></el-input>
          </p>
          <p>
            <span>门店位置：</span>
            <el-input
                size="small"
                style="width: 300px"
                v-model="data.storeLocation"
            ></el-input>
          </p>
          <p>
            <span>导航距离：</span>
            <el-input-number
                size="small"
                style="width: 300px"
                v-model="data.navigationDistance"
            ></el-input-number>
          </p>
        </div>
        <!--        新增单-->
        <div v-if="commissionTypeId == 6">
          <p>
            <span>拣货人固定提成总额：</span>
            <el-input-number
                size="small"
                style="width: 300px"
                v-model="data.totalCommission"
            ></el-input-number>
          </p>
          <p>
            <span>拣货相关人员：</span>
            <el-select
                multiple
                v-model="data.pickerList"
                filterable
                style="width: 300px"
                size="small"
                placeholder="请选择提成人员"
            >
              <el-option
                  v-for="(item, index) in userList"
                  :label="item.userName"
                  :value="item.id"
                  :key="index"
              ></el-option>
            </el-select>
          </p>
          <p>
            <span>发货相关人员：</span>
            <el-select
                multiple
                v-model="data.senderList"
                filterable
                style="width: 300px"
                size="small"
                placeholder="请选择提成人员"
            >
              <el-option
                  v-for="(item, index) in userList"
                  :label="item.userName"
                  :value="item.id"
                  :key="index"
              ></el-option>
            </el-select>
          </p>
          <p>
            <span>发货人固定提成总额：</span>
            <el-input-number
                size="small"
                style="width: 300px"
                v-model="data.senderCommission"
            ></el-input-number>
          </p>
        </div>
        <!--        仓库货架捡货提成(8)-->
        <div v-if="commissionTypeId == 8">
          <p>
            <span>是否有仓储架：</span>
            <!--            <el-radio-group :disabled="true" v-model="data.isStorageRack" style="width: 300px">-->
            <!--              <el-radio :label="0">否</el-radio>-->
            <!--              <el-radio :label="1">是</el-radio>-->
            <!--            </el-radio-group>-->
            <el-select
                size="small"
                :disabled="true"
                v-model="data.isStorageRack"
                style="width: 300px"
            >
              <el-option label="否" :value="0"></el-option>
              <el-option label="是" :value="1"></el-option>
            </el-select>
          </p>
          <p>
            <span>拣货组数：</span>
            <el-input-number
                :disabled="true"
                size="small"
                style="width: 300px"
                v-model="data.pickUpGroupNum"
            ></el-input-number>
          </p>
        </div>
        <!--       门店安装提成(9)-->
        <div v-if="commissionTypeId == 9">
          <p>
            <span>零时工数量：</span>
            <el-input-number
                size="small"
                style="width: 300px"
                v-model="data.tempWorkerNum"
            ></el-input-number>
          </p>
          <p>
            <span>营业区组数：</span>
            <el-input-number
                :disabled="true"
                size="small"
                style="width: 300px"
                v-model="data.installGroupNum"
            ></el-input-number>
          </p>
          <p>
            <span>仓储区组数：</span>
            <el-input-number
                :disabled="true"
                size="small"
                style="width: 300px"
                v-model="data.installGroupNumCk"
            ></el-input-number>
          </p>
        </div>
        <!--        门店拆店提成(10)-->
        <div v-if="commissionTypeId == 10">
          <p>
            <span>零时工数量：</span>
            <el-input-number
                size="small"
                style="width: 300px"
                v-model="data.tempWorkerNum"
            ></el-input-number>
          </p>
          <p>
            <span>营业区组数：</span>
            <el-input-number
                :disabled="true"
                size="small"
                style="width: 300px"
                v-model="data.azDisassembleCount"
            ></el-input-number>
          </p>
          <p>
            <span>仓储区组数：</span>
            <el-input-number
                :disabled="true"
                size="small"
                style="width: 300px"
                v-model="data.azDisstorageCount"
            ></el-input-number>
          </p>
        </div>
        <div v-if="commissionTypeId == 13">
          <p>
            <span>零时工数量：</span>
            <el-input-number
                size="small"
                style="width: 300px"
                v-model="data.tempWorkerNum"
            ></el-input-number>
          </p>
        </div>
        <div>
          <p>
            <span>备注：</span>
            <el-input
                size="small"
                placeholder="请输入备注"
                type="textarea"
                style="width: 300px"
                v-model="data.remark"
            ></el-input>
          </p>
        </div>
        <div
            style="width: 400px; margin-bottom: 50px"
            v-if="commissionTypeId && commissionTypeId != 11"
        >
          <p style="width: 100%"><span>凭证证明：</span></p>
          <el-upload
              class="upload-demo"
              drag
              ref="uploadRef"
              :headers="headers"
              :action="`${$apiHost}/common/fileImgUrl`"
              :on-success="onSuccess"
              :show-file-list="false"
              multiple
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
            <div class="el-upload__tip" slot="tip" style="color: #ff4949">
              请尽量上传有利于审核的凭证作为证明!
            </div>
          </el-upload>
          <div style="display: flex">
            <p v-for="(item, index) in proof">
              <el-image
                  :src="'https://' + item"
                  style="width: 35px; height: 35px"
                  :preview-src-list="proof.map((a) => 'https://' + a)"
              ></el-image>
              <span @click="_delete(index)"
              ><el-icon
                  class="el-icon-delete"
                  style="font-size: 14px"
              ></el-icon
              ></span>
            </p>
          </div>
        </div>
      </div>
      <span slot="footer">
        <el-button size="small" @click="addDialog = false">取消</el-button>
        <el-button
            size="small"
            type="primary"
            @click="_submit"
            v-prevent-re-click
        >提交</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import store from '../../../../store'

export default {
  name: 'add',
  data() {
    return {
      addDialog: false,
      addTabs: '1',
      systemList: [],
      saleNameList: [],
      commissionList: [],
      userList: [],
      oldList: [],
      newList: [],
      carData: [],
      orderId: {},
      title: '',
      orderMark: '',
      proof: [],
      disabledOp: false,
      commissionCount: '',
      areaData: [],
      oldPicker: [],
      newPicker: [],
      data: {
        storeLocation: '',
        tempWorkerNum: 0,
        senderCommission: 0,
        azGoodsCount: 0,
        installGroupNum: 0,
        navigationDistance: 0,
        dismantleGroupNum: 0,
        azDisstorageCount: 0,
        azDisassembleCount: 0,
        isStorageRack: 0,
        totalCommission: 0,
        pickUpGroupNum: 0,
        installGroupNumCk: 0,
        brandId: null, //品牌id
      },
      commissionTypeId: '',
      host: this.$imgHost,
      optionerList: [
        {name: '熊大', id: 1},
        {name: '熊er', id: 2},
      ],
      editableTabs: [
        {
          title: '第1条',
          name: '1',
          data: {
            fileList: [],
          },
        },
      ],
      tabIndex: 1,
    }
  },
  created() {
    document.addEventListener('paste', this.handlePaste)
  },
  computed: {
    headers() {
      return {
        token: this.token || window.$quinn.getStorage('token'),
      }
    },
  },
  methods: {
    handlePaste(event) {
      if (!this.addDialog) return
      const clipboardData = event.clipboardData || window.clipboardData
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i]

          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile()
            if (file) {
              this.uploadImage(file)
            }
          } else {
            this.$message.error('请拷贝图片!')
            break
          }
        }
      }
    },
    uploadImage(imageFile) {
      const formData = new FormData()
      formData.append('file', imageFile)
      axios
          .post(`${this.$apiHost}/common/fileImgUrl`, formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              token: store.state.token,
            },
          })
          .then((response) => {
            this.proof.push(response.data.result[0])
            this.fileList.push(response.data.result[0])
          })
          .catch((error) => {
          })
    },
    onSuccess(res) {
      if (res.code === 200 && res.result) {
        this.proof.push(res.result[0])
      }
    },
    _delete(index) {
      this.proof.splice(index, 1)
    },
    handleChange(val) {
      const selected = this.carData.find((item) => item.id === val)
      if (this.commissionTypeId == 2) {
        this.commissionCount = selected.pickCommission
      } else {
        this.commissionCount = selected.unloadCommission
      }
    },
    handleOpen(row) {
      this.addDialog = true
      // this.$refs.uploadRef.clearFiles()
      this.oldPicker = []
      this.newPicker = []
      this.data = this.$options.data.call(this).data
      this.proof = []
      if (!row) {
        this.title = '新增提成'
        this.disabledOp = false
        this.commissionTypeId = ''
        this.orderId = {}
      } else {
        this.disabledOp = true
        this.title = '分配人员'
        this.parentId = row.parentId
        this.commissionTypeId = row.commissionTypeId
        this.orderId = row.storeName
        this.orderMark = row.orderId
        this.$api
            .orderGetOrderInfoLikeName({storeName: row.storeName})
            .then((res) => {
              this.changeVal(res[0])
              if ([2, 3].includes(this.commissionTypeId)) return
              this.$api
                  .commissionGetCommissionConfig({id: this.commissionTypeId})
                  .then((res1) => {
                    switch (this.commissionTypeId) {
                      case 1:
                        this.commissionCount = res1.materialFixedAmount
                        break
                      case 4:
                        this.commissionCount = res1.storeUnloadFixedAmount
                        break
                      case 7:
                        this.commissionCount = res1.afterSaleFixedAmount
                        break
                    }
                  })
            })
      }
      this.getSystemType()
      this.getCommissionType()
      this.getUser()
      this.carList()
      this.getArea()
      this.getOldNewList()
    },
    getArea() {
      this.$api.areaLedgerAreaList().then((res) => {
        this.areaData = res
      })
    },
    getOldNewList() {
      const employeeType = [2, 1]
      const lists = ['newList', 'oldList']
      Promise.all(
          employeeType.map((employeeType, index) =>
              this.$api
                  .accountOldEmployeeList({employeeType, loginType: 4})
                  .then((res) => {
                    res.map((el) => (el.employeeType = employeeType))
                    this[lists[index]] = res
                  })
          )
      ).catch((error) => {
        console.error('Error', error)
      })
    },
    changeVal(val) {
      console.log(val, 'val')
      switch (this.commissionTypeId) {
        case 5:
          this.data.storeLocation = val.address
          break
        case 8:
          this.$api
              .commissionDetailsSelectPickupGroup({
                orderId: val.orderId,
              })
              .then((res) => {
                this.data.isStorageRack = res.isStorageRack
                this.data.pickUpGroupNum = res.jhGoodsCount || 0
              })
          break
        case 9:
          this.$api
              .commissionDetailsSelectPickupGroup({
                orderId: val.orderId,
              })
              .then((res) => {
                this.data.installGroupNum = res.azGoodsCount || 0
                this.data.installGroupNumCk = res.azStorageCount || 0
              })
          break
        case 10:
          this.$api
              .commissionDetailsSelectPickupGroup({
                orderId: val.orderId,
              })
              .then((res) => {
                this.data.azDisassembleCount = res.azDisassembleCount || 0
                this.data.azDisstorageCount = res.azDisstorageCount || 0
              })
          break
      }
    },
    inputChange(val) {
      if (val) {
        const params = {
          storeName: val,
        }
        this.$api.orderGetOrderInfoLikeName(params).then((res) => {
          this.saleNameList = res
        })
      }
    },
    getSystemType() {
      this.$api.orderGetSystemTypeVo().then((res) => {
        this.systemList = res
      })
    },
    getCommissionType() {
      this.$api.commissionGetCommissionTypes2().then((res) => {
        this.commissionList = res
      })
    },
    getUser() {
      this.$api.orderSelectInstallationUser({loginType: 4}).then((res) => {
        this.userList = res
      })
    },
    carList() {
      this.$api.vehicleGetVehicleModel().then((res) => {
        this.carData = res
      })
    },
    orderData() {
      this.$api
          .orderOrderList({pageNumber: 1, pageSize: 100000})
          .then((res) => {
            console.log(res)
          })
    },
    async changeType(val) {
      this.commissionCount = ''
      this.orderId = ''
      this.oldPicker = []
      this.newPicker = []
      this.data = this.$options.data.call(this).data
      this.proof = []
      if ([2, 3].includes(val)) return
      const res = await this.$api.commissionGetCommissionConfig({id: val})
      switch (val) {
        case 1:
          this.commissionCount = res.materialFixedAmount
          break
        case 4:
          this.commissionCount = res.storeUnloadFixedAmount
          break
        case 7:
          this.commissionCount = res.afterSaleFixedAmount
          break
      }
    },
    _submit() {
      switch (this.disabledOp) {
        case false:
          this.post(this.orderId.orderId)
          break
        case true:
          this.post(this.orderMark)
          break
      }
    },
    async post(c) {
      if (this.commissionTypeId == 9) {
        this.data.pickerList = this.oldPicker.concat(this.newPicker)
      }
      try {
        const apiMap = {
          false: this.$api.commissionDetailsAddCommissionDetails,
          true: this.$api.commissionDetailsDistribution,
        }
        const data = {
          ...this.data,
          commissionTypeId: this.commissionTypeId,
          proof: this.proof.join(','),
          orderId: c,
          parentId: this.parentId,
        }
        const apiFunc = apiMap[this.disabledOp]
        if (!apiFunc) return
        const res = await apiFunc(data)
        if (Number(res)) {
          this.$message.success('提交成功！')
          this.addDialog = false
          this.$emit('addStatus', 1)
        }
      } catch (err) {
        console.error('提交异常：', err)
      }
    },
  },
}
</script>

<style scoped lang="less">
/deep/ .el-dialog__header {
  background-color: #0f79e2;
  //border-top-left-radius: 20px;
  //border-top-right-radius: 20px;
}

/deep/ .el-input.is-disabled .el-input__inner {
  color: #777;
}

/deep/ .el-dialog__title {
  color: #fff;
}

/deep/ .el-tabs--left,
.el-tabs--right {
  height: 300px;
}

.content {
  display: flex;
  flex-direction: column;
  align-items: center;

  p {
    margin-bottom: 10px;

    span {
      display: inline-block;
      width: 100px;
    }
  }
}
</style>
